package com.rainy.sso.server.auth;

import com.rainy.sso.client.entity.*;
import com.rainy.sso.client.service.RolePermissionService;
import com.rainy.sso.client.service.UserRoleService;
import com.rainy.sso.client.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author liuqin on 2017/12/11
 */
public class AuthRealm extends AuthorizingRealm{

    @Resource
    private UserService userService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //String username = String.valueOf(principalCollection.fromRealm(getName()).iterator().next());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        if (user!=null){
            //User user = userService.queryUserByUserName(username);
            Set<Permission> permissions = user.getPermissions();
            Set<Role> roles = user.getRoles();
            if (CollectionUtils.isNotEmpty(roles)){
                info.setRoles(roles.stream().map(Role::getName).collect(Collectors.toSet()));
            }
            if (CollectionUtils.isNotEmpty(permissions)){
                permissions.forEach(permission -> {
                    info.addStringPermission(permission.getUrl());
                });
            }
        }
        return info;
    }

    /**
     * 认证，登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken  utoken=(UsernamePasswordToken) token;
        String username = utoken.getUsername();
        User user = userService.queryUserByUserName(username);
        return new SimpleAuthenticationInfo(user,
                user.getPswd(), getName());
    }
}
